import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

/*字节流响应图片*/
@WebServlet("/response4")
public class ResponseDemo4 extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String realPath = getServletContext().getRealPath("/img/wx.png");
        //1.创建字节缓冲输入流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath));
        //2.通过respose对象获取字节缓冲输出流
        ServletOutputStream sos = resp.getOutputStream();
        //3.传输图片
        byte[] bytes = new byte[1024];
        int len;
        while((len=bis.read(bytes))!=-1){
            sos.write(bytes,0,len);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
